package com.hsl.housaileibot001.ai.rag;

import com.hsl.housaileibot001.ai.service.AiChatService;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @Date 2025/10/18 17:33
 * @Author hsl
 */
// @Configuration
public class RagConfig {
    @Resource
    private EmbeddingStore<TextSegment> embeddingStore;
    @Resource
    private ChatModel qwenChatModel2;

    @Bean(name = "aiChatServiceRag")
    public AiChatService aiChatServiceRag() {
        // ------ RAG ------
        // 1. 加载文档
        List<Document> documents = FileSystemDocumentLoader.loadDocuments("src/main/resources/docs");
        // 2. 使用内置的 EmbeddingModel 转换文本为向量，然后存储到自动注入的内存 embeddingStore 中
        EmbeddingStoreIngestor.ingest(documents, embeddingStore);
        MessageWindowChatMemory chatMemory = MessageWindowChatMemory.withMaxMessages(10);
        // 构造 AI Service
        // RAG：从内存 embeddingStore 中检索匹配的文本片段
        return AiServices.builder(AiChatService.class)
                .chatModel(qwenChatModel2)
                .chatMemory(chatMemory)
                // RAG：从内存 embeddingStore 中检索匹配的文本片段
                .contentRetriever(EmbeddingStoreContentRetriever.from(embeddingStore))
                .build();
    }
}
